<template>
	<view class="jnpf-wrap jnpf-wrap-workflow">
		<addForm v-show="addStatus" ref="addFormRef" />
		<view v-show="!addStatus">
			<u-form :model="dataForm" ref="dataForm" :errorType="['toast']" label-position="left" label-width="190"
				label-align="left">
				<u-form-item label="还款单号" v-if="judgeShow('tl002')">
					<u-input v-model="dataForm.tl002" disabled></u-input>
				</u-form-item>
				<u-form-item label="人员" v-if="judgeShow('tl003')">
					<jnpf-user-select v-model="dataForm.tl003" @input="changeName"
						:disabled="judgeWrite('tl003')|| setting.readonly" />
				</u-form-item>
				<u-form-item label="部门" v-if="judgeShow('tl004')">
					<u-input v-model="dataForm.tl009" disabled></u-input>
				</u-form-item>
				<u-form-item label="还款金额合计" v-if="judgeShow('tl005')">
					<u-input v-model="dataForm.tl005" disabled></u-input>
				</u-form-item>
				<u-form-item label="还款日期" v-if="judgeShow('tl006')">
					<lys-date v-if="showte005" type="1" @cancleTime="showte005 = false"
						@submitTime="submitte005"></lys-date>
					<view style="display: flex;justify-content: space-between;width: 100%;">
						<view>
							{{dataForm.tl006}}
						</view>
						<view>
							<u-icon name="arrow-down-fill" color='#ccc' @click="showte005=true"
								:disabled="judgeWrite('tl006')|| setting.readonly"></u-icon>
						</view>
					</view>
				</u-form-item>

				<view class="jnpf-table" style="margin-top: 24rpx">
					<view class="jnpf-table-item" style="margin-bottom: 24rpx"
						v-for="(item, i) in dataForm.tableField109" :key="i">
						<u-form-item label="序号" style="background-color: aqua">
							{{ i + 1 }}
						</u-form-item>
						<u-form-item label="借款单号" v-if="judgeShow('tableField109-tn003')">
							<view style="display: flex;justify-content: space-between;width: 100%;">
								<view>
									{{item.tn003}}
								</view>
								<view>
									<u-icon name="arrow-down-fill" color='#ccc' @click="chioceOastdBox(index)"></u-icon>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="借款金额" v-if="judgeShow('tableField109-tn004')">
							<u-input v-model="item.tn004" disabled></u-input>
						</u-form-item>
						<!-- :disabled="
                        judgeWrite('tableField109') ||
                        judgeWrite('tableField109-tn004')|| setting.readonly
                      " -->
						<u-form-item label="借款日期" v-if="judgeShow('tableField109-tn005')">
							<lys-date v-if="showtn005" type="1" @cancleTime="showtn005 = false"
								@submitTime="submittn005"></lys-date>
							<view style="display: flex;justify-content: space-between;width: 100%;">
								<view>
									{{item.tn005}}
								</view>
								<view>
									<u-icon name="arrow-down-fill" color='#ccc' @click="handleshowtn005(index)"
										:disabled="
                        judgeWrite('tableField109') ||
                        judgeWrite('tableField109-tn005')|| setting.readonly
                      "></u-icon>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="姓名" v-if="judgeShow('tableField109-tn006')">
							<jnpf-user-select v-model="item.tn006" :disabled="
                        judgeWrite('tableField109') ||
                        judgeWrite('tableField109-tn006')|| setting.readonly
                      " />
						</u-form-item>
						<u-form-item label="已还款金额" v-if="judgeShow('tableField109-tn008')">
							<u-input v-model="item.tn008" disabled></u-input>
						</u-form-item>
						<u-form-item label="还款金额" v-if="judgeShow('tableField109-tn009')">
							<u-input v-model="item.tn009" :disabled="
                        judgeWrite('tableField109') ||
                        judgeWrite('tableField109-tn009')|| setting.readonly
                      "></u-input>
						</u-form-item>
						<u-form-item label="备注" v-if="judgeShow('tableField109-tn007')">
							<u-input v-model="item.tn007" :disabled="
                        judgeWrite('tableField109') ||
                        judgeWrite('tableField109-tn007')|| setting.readonly
                      "></u-input>
						</u-form-item>
					</view>
				</view>
			</u-form>
		</view>
		<u-popup v-model="popupshow" mode="bottom" height="50vh">
			<view class="content">
				<scroll-view :scroll-y="true" :scroll-x="true"
					style="height: 800rpx; white-space: nowrap;overflow-x: auto;">
					<zsf-table :radio='true' @getRow='getSelectData' ref="product" :title='productionQueueTitle'
						:data="tableList"></zsf-table>
				</scroll-view>
				<view class="confrim-btn">
					<u-button @click="close">确定</u-button>
				</view>
			</view>
		</u-popup>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import addForm from "./addForm.vue";
	import comMixin from "../mixin";
	import {
		getGoodsList,
		getCustomerList,
		Info,
		Create,
		Update,
	} from "@/api/apply/order";
	import {
		getOastl,
		BomcbListInit,
		putOastl,
		getOastdboxList
	} from "@/api/workFlow/flowBefore";
	import {
		getDictionaryDataSelector,
		getDataInterfaceDataInfo,
		getUserAll
	} from "@/api/common";
	export default {
		mixins: [comMixin],
		components: {
			addForm
		},
		computed: {
			getTb019Computed() {
				return (id) => {
					const options = this.options.filter((item) => id.includes(item.id));
					return options.length > 0 ? options[0].fullName : "";
				};
			},
		},
		watch: {
			'dataForm.tableField109': {
				handler(newVal) {
					let total = 0;
					console.log('newVal', newVal);
					newVal.forEach(item => {
						if (item.tn009) {
							total += parseFloat(item.tn009);
						}
					});
					this.dataForm.tl005 = total;
				},
				deep: true // 深度监听数组内部的变化
			}
		},
		data() {
			return {
				productionQueueTitle: [{
						title: "序号",
						key: "sid",
						width: '80',
					},
					{
						title: "借款单号",
						key: "ti002",
						width: '80',
					},
					{
						title: "借款金颔",
						key: "ti004",
						width: '80',
					},
					{
						title: "借款日期",
						key: "ti005",
						width: '80',
					},
					{
						title: "收款人",
						key: "ti008Name",
						width: '80',
					},

				],
				List: [],
				tableList: [],
				popupshow: false,
				opType: 0,
				showte005: false,
				show: false,
				dataForm: {},
				addStatus: "",
				id: "",
				showForm: [],
				formOperatesList: [],
				tb019Options: [],
				options: [{
						fullName: "必选，唯一",
						id: "1",
					},
					{
						fullName: "必选，至少一个",
						id: "2",
					},
					{
						fullName: "可选，唯一",
						id: "3",
					},
					{
						fullName: "任意选",
						id: "4",
					},
				],
				tl004Id: null,
			};
		},
		methods: {
			getSelectData(e) {
				this.List = [{
					...e.data
				}]
			},
			close() {
				this.popupshow = false;
				this.dataForm.tableField109.splice(this.index, 1);
				for (let i = 0; i < this.List.length; i++) {
					const e = this.List[i];
					//判断借款单号是否存在
					if (
						this.dataForm.tableField109.filter(o => o.tn003 === e.ti002).length >
						0
					) {
						return this.$refs.uToast.show({
							title: '该借款单号已存在！',
							type: 'error',
						})
					}
					let item = {
						tn003: e.ti002, //借款单号
						tn004: e.ti004, //借款金额
						tn005: e.ti005, //借款日期
						tn006: e.ti008, //姓名
						tn008: e.ti010, //已还款金额
						tn009: parseFloat(e.ti004 || 0) - parseFloat(e.ti010 || 0),
					};
					this.dataForm.tableField109.push(item);
				}
			},
			chioceOastdBox(index) {
				if (!this.dataForm.tl004) {
					this.$refs.uToast.show({
						title: '部门不能为空！',
						type: 'error',
					})
					return
				}
				this.index = index; //当前下标
				//报销部门
				var queryParam = {
					ti008: this.tl004Id || this.dataForm.tl003,
					currentPage: 1,
					pageSize: 500,
					sort: 'asc',
					sidx: 'TI001',
				};
				getOastdboxList(queryParam).then(res => {
					this.popupshow = true
					this.tableList = res.data.list.map((item, index) => {
						return {
							sid: index + 1,
							...item
						}
					})
				})
			},
			submittn005(time, type, timeInt) {
				let tn005 = time.split("-");
				this.dataForm.tableField109[this.index].tn005 = tn005[0] + tn005[1] + tn005[2]
				this.showtn005 = false;
			},
			submitte005(time, type, timeInt) {
				let tl006 = time.split("-");
				this.dataForm.tl006 = tl006[0] + tl006[1] + tl006[2]
				this.showte005 = false;
			},
			changeName(id) {
				getUserAll().then(res => {
					let item = res.data.filter(o => o.id === id)[0]
					this.tl004Id = item.id
					this.dataForm.tl004 = item.departmentId; //部门编号
					this.dataForm.tl009 = item.department; //部门名称
				})
			},
			init(data, id, flowFormContentJson, addStatus) {
				this.addStatus = addStatus
				this.opType = data.opType;
				this.setting = data;
				this.formOperatesList = data.formOperates;
				this.id = id;
				if (!this.addStatus) {
					this.getInfoFn(id);
				} else {
					this.$refs.addFormRef.getInfoFn(data)
				}
			},
			getInfoFn(id) {
				getOastl(id).then((res) => {
					if (res.code == 200) {
						this.dataForm = res.data;
						console.log('this.dataForm ', this.dataForm.tl004);
						this.getDataInterfaceDataInfoME001(this.dataForm.tl004);
						this.getDataInterfaceDataInfoMV001(this.dataForm.tl003);
					}
				});
			},
			judgeShow(id) {
				if (!this.setting.formOperates || !this.setting.formOperates.length)
					return true;
				let arr = this.setting.formOperates.filter(o => o.id === id) || [];
				if (!arr.length) return true;
				let item = arr[0];
				return item.read;
			},
			judgeWrite(id) {
				if (!this.setting.formOperates || !this.setting.formOperates.length)
					return false;
				let arr = this.setting.formOperates.filter(o => o.id === id) || [];
				if (!arr.length) return true;
				let item = arr[0];
				return !item.write;
			},
			queryChildBachelor(tb004) {
				let query = {
					tb004,
				};
				BomcbListInit(query).then((res) => {
					this.showForm = res.data;
					this.show = true;
				});
			},
			// 部门
			getDataInterfaceDataInfoME001(id) {
				let data = {
					id,
					interfaceId: "362111557984852549",
					propsValue: "ME001",
					relationField: "JoinStr",
				};
				getDataInterfaceDataInfo("362111557984852549", data).then((res) => {
					this.dataForm.tl004 = res.data.JoinStr;
				});
			},
			// 人员
			getDataInterfaceDataInfoMV001(id) {
				let data = {
					id,
					interfaceId: "445425382452126213",
					propsValue: "MV001",
					relationField: "JoinStr",
				};
				getDataInterfaceDataInfo("445425382452126213", data).then((res) => {
					this.dataForm.tl003 = res.data.JoinStr;
				});
			},
			selfGetInfo() {
				Info(this.setting.id).then((res) => {
					this.dataForm = res.data;
					if (this.dataForm.fileJson) {
						this.fileList = JSON.parse(this.dataForm.fileJson);
					}
				});
			},
			submit(eventType, config) {
				console.log('config===>', config);
				for (let i = 0; i < this.dataForm.tableField109.length; i++) {
					const e = this.dataForm.tableField109[i];
					if (
						parseFloat(e.tn009) >
						parseFloat(e.tn004) - parseFloat(e.tn008)
					) {
						return this.$refs.uToast.show({
							title: "[还款金额]不能大于[借款金额-已还款金额]！",
							type: 'error',
						})
					}
					if (parseFloat(e.tn008) > parseFloat(e.tn004)) {
						return this.$refs.uToast.show({
							title: "[已还款金额]不能大于[借款金额]！",
							type: 'error',
						});
					}
				}
				this.dataForm.flowId = config.flowId
				this.dataForm.flowState = eventType === "submit" ? 0 : 1;
				if (eventType === "audit" || eventType === "reject") {
					this.$emit("eventReceiver", this.dataForm, eventType);
					return;
				}
				let name = eventType === "submit" ? '提交' : '保存';
				uni.showModal({
					title: "提示",
					content: `您确定要${name}当前流程吗？`,
					success: (res) => {
						if (res.confirm) {
							this.selfHandleRequest();
						}
					},
				});
			},
			selfHandleRequest(flowId) {
				putOastl(this.dataForm.tl001, this.dataForm).then((res) => {
					uni.showToast({
						title: res.msg,
						complete: () => {
							setTimeout(() => {
								uni.$emit("refresh");
								uni.navigateBack();
							}, 1500);
						},
					});
				});
			},
			initData() {
				getGoodsList().then((res) => {
					this.goodsOptions = res.data.list;
				});
				getCustomerList().then((res) => {
					this.customerOptions = res.data.list;
				});
			},
			selfInit() {
				this.addGoods();
				this.addPlan();
			},
			onChange(e) {
				const user = e[0];
				this.dataForm.salesmanName = user.fullName;
			},
			addGoods() {
				const item = {
					goodsId: "",
					goodsCode: "",
					goodsName: "",
					specifications: "",
					unit: "",
					qty: "",
					price: "",
					amount: "",
					discount: null,
					cess: null,
					actualPrice: "",
					actualAmount: "",
					description: "",
				};
				this.dataForm.goodsList.push(item);
			},
			delGoods(index) {
				this.dataForm.goodsList.splice(index, 1);
			},
			addPlan() {
				const item = {
					receivableDate: "",
					receivableRate: "",
					receivableMoney: "",
					receivableMode: "",
					abstract: "",
				};
				this.dataForm.collectionPlanList.push(item);
			},
			delPlan(index) {
				this.dataForm.collectionPlanList.splice(index, 1);
			},
			onGoodsChange(e, i) {
				const goods = e[0];
				this.dataForm.goodsList[i] = {
					goodsId: goods.id,
					goodsCode: goods.code,
					goodsName: goods.text,
					specifications: goods.specifications,
					unit: goods.unit,
					qty: 1,
					price: goods.price,
					amount: goods.price,
					discount: 100,
					cess: 0,
					actualPrice: goods.price,
					actualAmount: goods.price,
					description: "",
				};
				this.$forceUpdate();
			},
			onCustomerChange(e) {
				const customer = e[0];
				this.dataForm.customerName = customer.text;
			},
			count(row) {
				//金额 = 数量*单价
				row.amount = this.jnpf.toDecimal(
					parseFloat(row.price) * parseFloat(row.qty)
				);
				//折扣价 = (单价*折扣)
				var discountPrice = row.price * (row.discount / 100);
				//实际单价 = 折扣价 * (1 + (税率 / 100))
				row.actualPrice = this.jnpf.toDecimal(
					discountPrice * (1 + row.cess / 100)
				);
				//实际金额
				row.actualAmount = this.jnpf.toDecimal(
					parseFloat(row.actualPrice) * parseFloat(row.qty)
				);
				this.$forceUpdate();
			},
		},
	};
</script>